import { fileURLToPath } from 'url'
import { ConfigEnv, defineConfig, loadEnv, UserConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import vueJSX from '@vitejs/plugin-vue-jsx'
import { viteMockServe } from 'vite-plugin-mock'
import VitePluginCompression from 'vite-plugin-compression'
import { createHtmlPlugin } from 'vite-plugin-html'
import { manualChunksPlugin } from 'vite-plugin-webpackchunkname'
import AutoImport from 'unplugin-auto-import/vite'
import Icons from 'unplugin-icons/vite'
import Components from 'unplugin-vue-components/vite'
import ElementPlus from 'unplugin-element-plus/vite'
import IconsResolver from 'unplugin-icons/resolver'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
import visualizer from 'rollup-plugin-visualizer'
import externalGlobals from 'rollup-plugin-external-globals'
// import brotli from 'rollup-plugin-brotli'

const globals = externalGlobals({
	moment: 'moment',
	echarts: 'echarts',
	lodash: 'lodash'
})

export default defineConfig(({ mode }: ConfigEnv): UserConfig => {
	// 获取当前工作目录
	const root = process.cwd()
	// 获取环境变量
	const env = loadEnv(mode, root)
	console.log(root, env)
	return {
		root,
		// 项目部署的基础路径
		base: './',
		publicDir: fileURLToPath(new URL('./public', import.meta.url)), // 无需处理静态资源位置
		assetsInclude: fileURLToPath(new URL('./src/assets', import.meta.url)), // 需要处理的静态资源位置
		css: {
			preprocessorOptions: {
				less: {
					additionalData: `@import url('@/styles/variable.less');`
				}
			}
		},
		plugins: [
			// Vue模板文件的编译插件
			vue(),
			// jsx文件编译插件
			vueJSX(),
			viteMockServe({
				// 如果接口为 /mocks/xxx 以 mock 开头就会被拦截响应配置的内容
				mockPath: 'mocks',
				enable: true
			}),
			// 开启ElementPlus自动引入CSS
			ElementPlus({}),
			// 自动引入组件及ICON
			AutoImport({
				// 自定义引入的框架
				imports: ['vue', 'vue-router', 'pinia'],
				eslintrc: {
					enabled: true
				},
				resolvers: [IconsResolver(), ElementPlusResolver()],
				dts: fileURLToPath(new URL('./types/auto-imports.d.ts', import.meta.url))
			}),
			// 自动注册组件
			Components({
				resolvers: [IconsResolver(), ElementPlusResolver()],
				dts: fileURLToPath(new URL('./types/components.d.ts', import.meta.url)),
				dirs: fileURLToPath(new URL('./src/components/auto', import.meta.url)),
				// vite-plugin-webpackchunkname插件可能导致生产环境样式问题
				include: [/\.vue$/, /\.vue\?/]
			}),
			// 自动安装图标
			Icons({
				autoInstall: true
			}),
			// br文件压缩
			// brotli({}),
			// 文件压缩
			VitePluginCompression({
				threshold: 20 * 1024, // 超过20kb再压缩
				ext: '.gz',
				algorithm: 'gzip' // 压缩算法
			}),
			createHtmlPlugin({
				inject: {
					data: {
						momentScript: '<script src="https://cdn.bootcdn.net/ajax/libs/moment.js/2.30.1/moment.min.js"></script>',
						echartsScript: '<script src="https://cdn.bootcdn.net/ajax/libs/echarts/5.6.0/echarts.min.js"></script>',
						lodashScript: '<script src="https://cdn.bootcdn.net/ajax/libs/lodash.js/4.17.21/lodash.min.js"></script>'
					}
				}
			}),
			// 用来解决vite中实现webpack对注解webpackChunkName的功能
			manualChunksPlugin()
		],
		server: {
			host: true,
			port: 9000,
			open: false,
			cors: true,
			proxy: {
				// 以/api开发发送的请求会被转发到http://xxxx:9000
				[env.VITE_APP_API_BASE_URL]: {
					target: 'http://localhost:9000',
					changeOrigin: true
					// 发送请求时将/api 替换为 ''
					// rewrite: path => path.replace(/^\/api/, '')
				},
				[env.VITE_APP_MOCK_BASE_URL]: {
					target: 'http://localhost:9000',
					changeOrigin: true
					// 发送请求时将/api 替换为 ''
					// rewrite: (path) => path.replace(/^\/api/, '')
				}
			}
		},
		build: {
			sourcemap: false,
			// 打包大小超过400kb 警告
			chunkSizeWarningLimit: 400,
			rollupOptions: {
				// 打包入口文件 根目录下的index.html
				input: {
					index: fileURLToPath(new URL('./index.html', import.meta.url))
				},
				// experimentalLogSideEffects: true,
				treeshake: {
					preset: 'recommended'
				},
				output: {
					experimentalMinChunkSize: 20 * 1024,
					// // 业务模块放在index下，但三方包放到vendor下
					manualChunks(id: string) {
						// 少数页面在使用  所有单独打包最优
						if (id.includes('html2canvas')) return 'html2canvas'
						if (id.includes('node_modules')) return 'vendor'
						// return 'index'
					},
					chunkFileNames: 'static/js/[name]-[hash].js',
					entryFileNames: 'static/js/[name]-[hash].js',
					assetFileNames: 'static/[ext]/[name]-[hash].[ext]'
				},
				external: ['moment', 'echarts', 'lodash'],
				plugins: [visualizer(), globals]
				// 静态资源分类打包
				// output: {
				// 	format: 'esm',
				// 	chunkFileNames: 'static/js/[name]-[hash].js',
				// 	entryFileNames: 'static/js/[name]-[hash].js',
				// 	assetFileNames: 'static/[ext]/[name]-[hash].[ext]'
				// }
			}
		},
		resolve: {
			// 配置别名
			alias: {
				'@': fileURLToPath(new URL('./src', import.meta.url)),
				'#': fileURLToPath(new URL('./types', import.meta.url))
			}
		}
	}
})
